package medium;

public class AddTwoNumbers {
	public static void main(String[] args) {
		
	}
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    	if(l1 == null && l2 != null)
    		return l2;
    	else if(l1 != null && l2 == null)
    		return l1;
    	else if(l1 == null && l2 == null)
    		return null;
		int value = l1.val + l2.val;
		int rank = 0;
		if(value >= 10)
		{
			value -= 10;
			rank = 1;
		}
    	ListNode result = new ListNode(value);
    	l1 = l1.next;
    	l2 = l2.next;
    	ListNode p = result;
    	int sign = 0;
    	while(true){
    		if(l1 == null){
    			sign = 1;
    			break;
    		}else if(l2 == null){
    			sign = 2;
    			break;
    		}
    		value = l1.val + l2.val + rank;
    		rank = 0;
    		if(value >= 10)
    		{
    			value -= 10;
    			rank = 1;
    		}
    		ListNode newNode = new ListNode(value);
    		p.next = newNode;
    		p = p.next;
    		p.next = null;
    		l1 = l1.next;
    		l2 = l2.next;

    	}
    	if(sign == 1)
    		while(l2 != null){
    			value = l2.val + rank;
    			rank = 0;
    			if(value >= 10){
    				value -= 10;
    				rank = 1;
    			}
    			ListNode newNode = new ListNode(value);
    			l2 = l2.next;
        		p.next = newNode;
        		p = p.next;
        		p.next = null;
    		}
    	else if(sign == 2)
    		while(l1 != null){
    			value = l1.val + rank;
    			rank = 0;
    			if(value >= 10){
    				value -= 10;
    				rank = 1;
    			}
    			ListNode newNode = new ListNode(value);
    			l1 = l1.next;
        		p.next = newNode;
        		p = p.next;
        		p.next = null;
    		}
    	if(rank == 1){
			ListNode newNode = new ListNode(rank);
			rank = 0;
    		p.next = newNode;
    		p = p.next;
    		p.next = null;
    	}
        return result;
    }
}
class ListNode {
     int val;
     ListNode next;
     ListNode(int x) { val = x; }
 }
